package com.example.demo.services;

import com.example.demo.entity.Product.ProductDetail;
import com.example.demo.entity.Product.WorkArea;
import com.example.demo.repository.ProductDetailRepository;
import com.example.demo.repository.WorkAreaCNRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.ParameterMode;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.StoredProcedureQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ProductDetailService {

    @PersistenceContext
    private final EntityManager entityManager;

    private final ProductDetailRepository productDetailRepository;
    private final WorkAreaCNRepository workAreaCNRepository;

    public ProductDetailService(EntityManager entityManager, ProductDetailRepository productDetailRepository, WorkAreaCNRepository workAreaCNRepository) {
        this.entityManager = entityManager;
        this.productDetailRepository = productDetailRepository;
        this.workAreaCNRepository = workAreaCNRepository;
    }

    @Transactional
    public boolean addDetail(ProductDetail productDetail) {
        try {
            productDetailRepository.save(productDetail);
            entityManager.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public ProductDetail fetchDetail(String billNo) {
        return productDetailRepository.fetchDetail(billNo);
    }

    public WorkArea getAreaName(String workingAreaCode) {
        return workAreaCNRepository.getAreaName(workingAreaCode);
    }

    public String getBillNumber(String billName) {

        LocalDateTime operationDate = LocalDateTime.now();

        StoredProcedureQuery query = entityManager.createStoredProcedureQuery("JJG_get_bill_number");
        query.registerStoredProcedureParameter("bill_name", String.class, ParameterMode.IN);
        query.registerStoredProcedureParameter("operation_date", LocalDateTime.class, ParameterMode.IN);
        query.registerStoredProcedureParameter("bill_number", String.class, ParameterMode.OUT);
        query.registerStoredProcedureParameter("ok", Long.class, ParameterMode.OUT);  //输出参数

        query.setParameter("bill_name", billName);
        query.setParameter("operation_date", operationDate);

        Long ok = (Long) query.getOutputParameterValue("ok");
        String billNo = (String) query.getOutputParameterValue("bill_number");
        //System.out.println(ok + "," + billNo);
        query.execute();

        if (ok == 1){
            return billNo;
        }
        return "取单号时出错";
    }
}
